import 'dart:async';
import 'dart:typed_data';

import 'package:audio_session/audio_session.dart';
import 'package:audio_spectrum/audio_spectrum.dart';
import 'package:audio_spectrum_example/RecordPainter.dart';
import 'package:flutter/material.dart';
import 'package:permission_handler/permission_handler.dart';

class FlutterSound extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _FlutterSoundState();
}

class _FlutterSoundState extends State<FlutterSound> {
  List<double>? fft;

  late AudioSpectrum audioSpectrum;

  @override
  void initState() {
    super.initState();
    // startRecord();
    audioSpectrum = AudioSpectrum();

  }

  start() async {
    var status = await Permission.microphone.request();

    audioSpectrum.startRecord();
  }

  stop() {
    audioSpectrum.stopRecord();
  }

  @override
  void dispose() {
    stop();
    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(''),
      ),
      body: Center(
        child: Column(
          children: [
            Row(
              children: [
                TextButton(
                    onPressed: () {
                      start();
                    },
                    child: const Text('开始录音')),
                TextButton(
                    onPressed: () {
                      stop();
                    },
                    child: const Text('结束录音')),
              ],
            ),
            fft != null
                ? CustomPaint(
                    painter: RecordPainter(fft!),
                    size: Size(MediaQuery.of(context).size.width, 500),
                  )
                : const SizedBox()
          ],
        ),
      ),
    );
  }
}
